const { query } = require('../../../lib/db');
const { authenticateToken } = require('../../../lib/auth');

async function handler(req, res) {
  try {
    if (req.method === 'GET') {
      return await getTicketOptions(req, res);
    }
    
    return res.status(405).json({
      success: false,
      message: '方法不允许'
    });
  } catch (error) {
    console.error('工单选项API错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

// 获取工单创建所需的所有选项数据
async function getTicketOptions(req, res) {
  try {
    // 并行查询所有选项数据
    const [
      applications,
      modules,
      productCategories,
      tags,
      supportStaff,
      solutionTemplates
    ] = await Promise.all([
      // 获取应用列表
      query(`
        SELECT id, name, code, description 
        FROM applications 
        WHERE status = 1 
        ORDER BY name
      `),
      
      // 获取模块列表
      query(`
        SELECT m.id, m.name, m.code, m.description, m.application_id,
               a.name as application_name, a.code as application_code
        FROM modules m
        LEFT JOIN applications a ON m.application_id = a.id
        WHERE m.status = 1 AND a.status = 1
        ORDER BY a.name, m.name
      `),
      
      // 获取产品分类列表
      query(`
        SELECT id, name, code, parent_id, level, description
        FROM product_categories 
        WHERE status = 1 
        ORDER BY level, sort_order, name
      `),
      
      // 获取标签列表
      query(`
        SELECT id, name, color, description, usage_count
        FROM tags 
        ORDER BY usage_count DESC, name
      `),
      
      // 获取支持人员列表
      query(`
        SELECT id, name, department, email
        FROM users 
        WHERE role IN ('support', 'administrator') AND status = 1
        ORDER BY name
      `),
      
      // 获取解决方案模板
      query(`
        SELECT id, title, content, category, tags, usage_count
        FROM solution_templates 
        WHERE is_public = 1
        ORDER BY usage_count DESC, title
        LIMIT 50
      `)
    ]);

    // 组织模块数据 - 按应用分组
    const modulesByApplication = {};
    modules.forEach(module => {
      if (!modulesByApplication[module.application_id]) {
        modulesByApplication[module.application_id] = [];
      }
      modulesByApplication[module.application_id].push({
        id: module.id,
        name: module.name,
        code: module.code,
        description: module.description
      });
    });

    // 组织产品分类数据 - 构建树形结构
    const categoryTree = buildCategoryTree(productCategories);

    // 添加枚举选项
    const enumOptions = {
      incident_levels: [
        { value: 'low', label: '低' },
        { value: 'medium', label: '中' },
        { value: 'high', label: '高' },
        { value: 'urgent', label: '紧急' }
      ],
      priorities: [
        { value: 'low', label: '低' },
        { value: 'medium', label: '中' },
        { value: 'high', label: '高' },
        { value: 'urgent', label: '紧急' }
      ],
      urgencies: [
        { value: 'low', label: '低' },
        { value: 'medium', label: '中' },
        { value: 'high', label: '高' },
        { value: 'urgent', label: '紧急' }
      ],
      ticket_types: [
        { value: 'incident', label: '事件' },
        { value: 'request', label: '请求' },
        { value: 'problem', label: '问题' },
        { value: 'change', label: '变更' }
      ],
      source_types: [
        { value: 'web', label: '网页' },
        { value: 'mobile', label: '移动端' },
        { value: 'api', label: 'API' },
        { value: 'email', label: '邮件' },
        { value: 'phone', label: '电话' },
        { value: 'other', label: '其他' }
      ],
      impact_scopes: [
        { value: 'individual', label: '个人' },
        { value: 'department', label: '部门' },
        { value: 'company', label: '公司' },
        { value: 'external', label: '外部' }
      ],
      statuses: [
        { value: 'pending', label: '待处理' },
        { value: 'in_progress', label: '处理中' },
        { value: 'resolved', label: '已解决' },
        { value: 'closed', label: '已关闭' },
        { value: 'cancelled', label: '已取消' }
      ]
    };

    res.status(200).json({
      success: true,
      data: {
        applications,
        modules: modulesByApplication,
        productCategories: categoryTree,
        tags,
        supportStaff,
        solutionTemplates,
        enums: enumOptions
      }
    });
  } catch (error) {
    console.error('获取工单选项失败:', error);
    res.status(500).json({
      success: false,
      message: '获取工单选项失败'
    });
  }
}

// 构建分类树形结构
function buildCategoryTree(categories) {
  const categoryMap = {};
  const tree = [];

  // 创建分类映射
  categories.forEach(category => {
    categoryMap[category.id] = {
      ...category,
      children: []
    };
  });

  // 构建树形结构
  categories.forEach(category => {
    if (category.parent_id) {
      if (categoryMap[category.parent_id]) {
        categoryMap[category.parent_id].children.push(categoryMap[category.id]);
      }
    } else {
      tree.push(categoryMap[category.id]);
    }
  });

  return tree;
}

export default authenticateToken(handler);